import * as crypto from "crypto";
import axios from "axios";

/**
 *
 * @param data 待加密数据
 * @param key 密钥支持32 位 输入64为会截取前32位
 * @param outputEncoding 输出编码方式默认为base64，当在url上时使用hex
 * */

export function aesEncode(data, key, outputEncoding) {
    // 本地生成的密钥到达了64位，aes不支持。服务端生成AES的密钥会限制长度不超过32位，会截断一半，这里如果需要一样，同样也需要截断
    if (key.length === 64) {
        let key1 = new Uint8Array(32);
        for (let i = 0; i < 64; i++) {
            key1[i] = key[i];
        }
        key = key1;
    }
    let cipher = crypto.createCipheriv('aes-256-ecb', key, "");
    //decipher.setAutoPadding(true);
    cipher.update(data, "utf-8");
    return cipher.final(outputEncoding ? outputEncoding : 'base64')
}

/**
 *
 * @param data 带解密数据，base64
 * @param key 密钥支持32 位 输入64为会截取前32位
 * @param outputEncoding 输出编码方式默认为base64，当在url上时使用hex
 * */

export function aesDecrypt(data, key, outputEncoding) {
    // 本地生成的密钥到达了64位，aes不支持。服务端生成AES的密钥会限制长度不超过32位，会截断一半，这里如果需要一样，同样也需要截断
    if (key.length === 64) {
        let key1 = new Uint8Array(32);
        for (let i = 0; i < 64; i++) {
            key1[i] = key[i];
        }
        key = key1;
    }

    let decipher = crypto.createDecipheriv('aes-256-ecb', key, "");
    //decipher.setAutoPadding(true);
    decipher.update(data, "base64");
    return decipher.final(outputEncoding ? outputEncoding : 'utf-8')
}
function keyAgreeByResponse(data) {
    let g = data.g, p = data.p, k = data.k
// 创建客户端的DH实例

    const client = crypto.createDiffieHellman(Buffer.from(p, 'base64'), Buffer.from(g, 'base64'));
// 产生公、私钥对，Yb = a^Xb mod p
    client.generateKeys();
    let secret = client.computeSecret(Buffer.from(k, 'base64'));
    let publicKey = client.getPublicKey();
    return {
        secret, publicKey: publicKey.toString('base64'), exchangeSessionId: data.exchangeSessionId
    }
}

export function doExchange(next, onError) {

    let url = '/sensitiveData/exchangeRequest';
    if (process.env.NODE_ENV === 'development') {
        url = window.dev.httpUrlBase + url;
    }
    axios.get(url).then((response) => {
            let data = response.data;
            let keyAgreeResult = keyAgreeByResponse(data);
            next(keyAgreeResult, aesEncode)
        }
    ).catch(onError ? onError : console.log)
}

const dhPublicKey = "dhPublicKey";

export function doExchangeByCachePk(next) {
    let dhKeyString = localStorage.getItem(dhPublicKey);
    let dhKey = JSON.parse(dhKeyString);
    let keyAgreeResult = keyAgreeByResponse(dhKey);
    next(keyAgreeResult, aesEncode)
}

export default dhPublicKey;